package com.wm.practice;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: FutureApiDemo
 * @Description: Future优缺点
 * @Author: Deamer
 * @Date: 2022/8/28 11:08
 **/
public class FutureApiDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<String> futureTask = new FutureTask<>(() -> {
            System.out.println(Thread.currentThread().getName() + "\t 子线程 come in");
            TimeUnit.SECONDS.sleep(5);
            return "task over";
        });
        Thread thread = new Thread(futureTask, "t1");
        thread.start();

        // getApi(futureTask);

        //1-------  System.out.println(futureTask.get(3,TimeUnit.SECONDS));//只愿意等3秒，过了3秒直接抛出异常
        //2-------更健壮的方式-------轮询方法---等副线程拿到才去get()
        //但是也会消耗cpu资源
        while (true) {
            if (futureTask.isDone()) {
                System.out.println(futureTask.get());
                break;
            } else {
                // 暂停毫秒数
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("正在处理任务，请稍后");
            }
        }
    }

    private static void getApi(FutureTask<String> futureTask) {
        // System.out.println(Thread.currentThread().getName() + "\t 主线程忙别的任务");
        try {
            System.out.println(futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "\t 主线程忙别的任务");
    }
}
